import 'package:common_utils/common_utils.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/Xwidgets/ad_box.dart';
import 'package:yp/Xwidgets/bottom_sheet.dart';
import 'package:yp/Xwidgets/cache_image.dart';
import 'package:yp/Xwidgets/navigation_bar.dart';
import 'package:yp/config/config.dart';
import 'package:yp/config/style.dart';
import 'package:yp/helper.dart';
import 'package:yp/pages/sec_kill/state.dart';
import 'package:yp/router.dart';
import 'package:yp/services/api.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:yp/utils/util.dart';
import 'logic.dart';

/// 秒杀活动
class SeckillHome extends StatefulWidget {
  const SeckillHome({Key key}) : super(key: key);

  @override
  _SeckillHomeState createState() => _SeckillHomeState();
}

class _SeckillHomeState extends State<SeckillHome> with TickerProviderStateMixin {
  final SecKillLogic logic = Get.put(SecKillLogic());
  final SecKillState state = Get.find<SecKillLogic>().state;

  // var _tabList = [];
  // TabController primaryTC;
  // int indicatorIndex = 0;

  @override
  void initState() {
    super.initState();
    print('primaryTC');
    state.primaryTC = TabController(length: 0, vsync: this);
    if (SpUtil.getInt('storeShopNum') == 0 || SpUtil.getInt('storeShopNum') == null) {
      var params = {
        'hash_code': Config.hashCode1,
      };
      print('+++++******++++++++++++ 111111111 ++++++++++++');
      Api.pingTaiZongDian(params).listen((event) {
        // print('===========  首页  ===========  $event');
        LogUtil.d("===========  首页  ===========：$event");
        if (event['code'] == 0) {
          List list = event['express_shops'];
          if (list.length > 0) {
            Map<String, dynamic> expressMap = list[0];
            SpUtil.putInt('storeShopNum', expressMap['ec_shop_num_id']); //  门店id
            _init();
          }
        }
      }, onError: (error) {
        print('+++++****** 首页 ++++++++++++ 失败 ++++++++++++ error = $error');
      });
    } else {
      print('+++++******++++++++++++ 222222222 ++++++++++++');
      _init();
    }
  }

  void _init() {
    var parameter = Get.parameters['cs'];
    Map<String, dynamic> results = Get.arguments!=null?Get.arguments['model']:null;
    if(results!=null){
        state.secKillEvent = results['results'];
        logic.setSlideshow(state.secKillEvent, 0);
        int shouci = 0;
        state.tabList = [];
      for (var i = 0; i < (state?.secKillEvent?.length ?? 0); i++) {
        // state.secKillEvent[i]['ecactivity_name'] = '14:00';
        var ss = state.secKillEvent[i]['series'].toString();
        if (parameter!=null&&parameter==ss) {
          shouci = i;
          state.indicatorIndex = i;
        }
        Tab tab = Tab(
            child: Column(children: [
          Text(state.secKillEvent[i]['ecactivity_name'], style: TextStyle(fontSize: EsSizes.MD, fontWeight: EsFontWeights.SemiBold)),
          // Text(_textState(state.secKillEvent[i]['start_time']),
          //     style: TextStyle(
          //         fontSize: EsSizes.XS, fontWeight: EsFontWeights.Normal))
        ]));
        state.tabList.add(tab);
      }

      // 首次查询商品
      logic.queryProduct(shouci);

      // print('=========)))))))========${state.tabList.length}');
      state.primaryTC = TabController(initialIndex:shouci,length: state?.tabList?.length ?? 0, vsync: this);

      state.primaryTC.addListener(() {
        print('state.primaryTC.index');
        print(state.primaryTC.index);
        if (state.primaryTC.index.toDouble() == state.primaryTC.animation.value) {
          logic.queryProduct(state.primaryTC.index);

          if (mounted) {
            setState(() {
              state.indicatorIndex = state.primaryTC.index;
              state.imageMap = [];
              logic.setSlideshow(state.secKillEvent, state.indicatorIndex);
            });
          }
        }
      });
      setState(() {});
      return;
    }
    var params = {
      "use_platform": 2,
      "sql_id": "DS-0001-50",
      "input_param": {
        "app_approve": 1,
        // "ec_shop_num_id": SpUtil.getInt('storeShopNum'),
        "ec_shop_num_id": SpUtil.getInt('storeShopNum'),
        "ecactivity_classify": 2,
        "ecactivity_status": 1
      },
      "page_num": 1,
      "page_size": 100
    };

    LogUtil.d("++++++返回类目参数++++++：$params");
    Api.toSecKillPage(params).listen((event) {
      LogUtil.d("++++++返回类目数据++++++：$event");
      if (event['code'] == 0) {
        state.secKillEvent = event['results'];
        logic.setSlideshow(state.secKillEvent, 0);
      }
      int shouci = 0;
      state.tabList = [];
      for (var i = 0; i < (state?.secKillEvent?.length ?? 0); i++) {
        // state.secKillEvent[i]['ecactivity_name'] = '14:00';
        var ss = state.secKillEvent[i]['series'].toString();
        if (parameter!=null&&parameter==ss) {
          shouci = i;
          state.indicatorIndex = i;
        }
        Tab tab = Tab(
            child: Column(children: [
          Text(state.secKillEvent[i]['ecactivity_name'], style: TextStyle(fontSize: EsSizes.MD, fontWeight: EsFontWeights.SemiBold)),
          // Text(_textState(state.secKillEvent[i]['start_time']),
          //     style: TextStyle(
          //         fontSize: EsSizes.XS, fontWeight: EsFontWeights.Normal))
        ]));
        state.tabList.add(tab);
      }
      state.primaryTC = TabController(initialIndex:shouci,length: state?.tabList?.length ?? 0, vsync: this);
      // 首次查询商品
      logic.queryProduct(shouci);

      state.primaryTC.addListener(() {
        print('state.primaryTC.index');
        print(state.primaryTC.index);
        if (state.primaryTC.index.toDouble() == state.primaryTC.animation.value) {
          logic.queryProduct(state.primaryTC.index);

          if (mounted) {
            setState(() {
              state.indicatorIndex = state.primaryTC.index;
              state.imageMap = [];
              logic.setSlideshow(state.secKillEvent, state.indicatorIndex);
            });
          }
        }
      });
      setState(() {});
    });
  }

  String _textState(String startTime) {
    DateTime nowTime = DateTime.now();
    DateTime dateTime = DateTime.parse(startTime);
    int hour = dateTime.hour % 2 > 0 ? ((dateTime.hour >= 1 ? dateTime.hour : 0) - 1) : dateTime.hour;
    int now = nowTime.hour % 2 > 0 ? ((nowTime.hour >= 1 ? nowTime.hour : 0) - 1) : nowTime.hour;
    if (hour >= 16) {
      hour = hour - 2 * ((hour - 16) ~/ 2);
    }
    return now > hour ? '已经结束' : ((now - hour).abs() > 1 ? '即将开始' : '正在秒杀');
  }

  @override
  void dispose() {
    state.primaryTC.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // ScreenUtil.init(
    //     BoxConstraints(
    //         maxWidth: MediaQuery.of(context).size.width,
    //         maxHeight: MediaQuery.of(context).size.height),
    //     designSize: Size(750, 1334),
    //     orientation: Orientation.portrait);
    return Stack(
      children: [
        Scaffold(
            appBar: YPXNavigationBar(
              '秒杀活动',
              showLine: false,
              backgroundColor: EsColors.Primary,
              backBtnColor: EsColors.White,
              titleColor: EsColors.White,
              showBack: kIsWeb ? false : true,
              onPressed: () {
                if (kIsWeb == true) {
                  Get.offAllNamed(RouteConfig.main);
                } else {
                  Get.back();
                }
              },
              actions: <Widget>[
                kIsWeb != true
                    ? IconButton(
                        icon: Icon(Icons.share),
                        color: Colors.white70,
                        onPressed: () {
                          var model;
                          var shareUrl;
                          print('分享路径');

                          print(state.actMap);
                            shareUrl = Config.H5_URL+'&isGoSeckillAct=true&id='+state.actMap['ecactivity_id'].toString()+'&currentShopId='+state.shopId.toString();


                          YpBottomSheet.showShareGift(context, (selectIndex, selectString, {info, list}) {
                            print(selectIndex);

                            model = fluwx.WeChatShareWebPageModel(
                              shareUrl,
                              title:state.actMap['ecactivity_name'],
                              description: state.actMap['share_desc'],
                              thumbnail: fluwx.WeChatImage.network(
                                  state.actMap['share_images']),
                              scene: selectIndex == 0 ? fluwx.WeChatScene.SESSION : fluwx.WeChatScene.TIMELINE,
                            );
                            fluwx.shareToWeChat(model);
                          }, title: '秒杀活动');
                        })
                    : Container(),
              ],
            ),
            body: GetBuilder<SecKillLogic>(builder: (logic) {
              return _buildScaffoldBody();
            })),
        if (state.showTip)
          InkWell(
            onTap: () {
              setState(() {
                state.showTip = !state.showTip;
              });
            },
            child: Container(
              color: Colors.black45.withOpacity(.75),
              child: Center(
                  child: Text(
                "请点击右上角的'...'\n然后选择在浏览器打开",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                ),
                textAlign: TextAlign.center,
              )),
            ),
          ),
      ],
    );
  }

  Widget _buildScaffoldBody() {
    return ExtendedNestedScrollView(
      headerSliverBuilder: (BuildContext c, bool f) {
        return <Widget>[
          SliverToBoxAdapter(child: _header()),
          SliverToBoxAdapter(child: _adbox()),
        ];
      },
      pinnedHeaderSliverHeightBuilder: () => 0,
      onlyOneScrollInBody: false,
      body: state.tabList.length > 0 ? TabBarView(controller: state.primaryTC, children: List<Widget>.generate(state?.tabList?.length ?? 0, (int index) => _infoList(index))) : Container(),
    );
  }

  Widget _header() {
    return Container(
      padding: EdgeInsets.only(left: setWidth(10), right: setWidth(10)),
      color: EsColors.Primary,
      child: TabBar(
        controller: state.primaryTC,
        labelPadding: EdgeInsets.zero,
        labelColor: EsColors.White,
        isScrollable: true,
        unselectedLabelColor: EsColors.Fill,
        indicatorSize: TabBarIndicatorSize.label,
        indicatorWeight: 0,
        indicator: const ExtendedUnderlineTabIndicator(borderSide: BorderSide(color: EsColors.Primary, width: 0)),
        tabs: List<Widget>.generate(
          state?.tabList?.length ?? 0,
          (int index) => Container(
            child: Text('${state.secKillEvent[index]['ecactivity_name']}'),
            padding: EdgeInsets.only(
              left: setWidth(8),
              right: setWidth(8),
            ),
            decoration: BoxDecoration(color: state.indicatorIndex == index ? EsColors.White.withOpacity(0.5) : EsColors.Primary, borderRadius: BorderRadius.circular(16.w)),
          ),
          /* Stack(
                  children: [
                    SizedBox(width: MediaQuery.of(context).size.width / 4),
                    Positioned(
                        bottom: 18.w,
                        left: 28.w,
                        right: 28.w,
                        child: Container(
                          height: 36.w,
                          decoration: BoxDecoration(
                              color: state.indicatorIndex == index
                                  ? EsColors.White.withOpacity(0.5)
                                  : EsColors.Primary,
                              borderRadius: BorderRadius.circular(16.w)),
                        )),
                    Positioned(
                        child: Padding(
                      padding: const EdgeInsets.only(left: 10),
                      child: Row(
                        children: [
                          Container(
                              // width: MediaQuery.of(context).size.width / 4 - 3,
                              child: Center(
                                  child: state?.tabList[index] ?? SizedBox())),
                          Container(
                              color: EsColors.Fill.withOpacity(0.5),
                              width: index + 1 == (state?.tabList?.length ?? 0)
                                  ? 0
                                  : 1,
                              height: 20.w)
                        ],
                      ),
                    ))
                  ],
                ) */
        ),
      ),
    );
  }

  /// 广告位
  Widget _adbox() {
    return Stack(children: [
      SizedBox(
        height: 140,
        width: double.infinity,
      ),
      Positioned(
        child: Container(
          height: 20,
          width: double.infinity,
          child: Container(decoration: BoxDecoration(color: EsColors.Primary, borderRadius: BorderRadius.only(bottomLeft: Radius.circular(30), bottomRight: Radius.circular(30)))),
        ),
      ),
      if (state.imageMap.length > 0)
        Positioned(
          child: AdBox(
            imageList: state.imageMap,
            aspectRatio: 355 / 145,
            adKey: 'Adv',
            height: 145,
            borderRadius: 6,
            margin: EdgeInsets.fromLTRB(12.0, 4, 12.0, 0),
          ),
        )
    ]);
  }

  /// 下边对应的列表
  Widget _infoList(int index) {
    return ListView.builder(
        itemBuilder: (context, index) {
          return _item(index);
        },
        itemCount: state.products.length);
  }

  Widget _item(int index) {
    return Container(
      margin: EdgeInsets.fromLTRB(20.w, 26.w, 20.w, 0),
      padding: EdgeInsets.all(20.w),
      decoration: EsDecoration.BoxShadowWithRadius,
      alignment: Alignment.center,
      child: GestureDetector(
        onTap: () {
          var shop_num_id =Get.arguments!=null? Get.arguments['model']['results'][index]['ec_shop_num_id']:null;
          var itemNumId = state.products[index]['item_num_id'].toString();
          var styleNumId = state.products[index]['style_num_id'].toString();
          var shopId = shop_num_id==null?SpUtil.getInt('storeShopNum'):shop_num_id;
          var ecStyleNumId = state.products[index]['ec_style_num_id'].toString();
          var typeIndex = state.products[index]['is_pre_sale']!=null?state.products[index]['is_pre_sale']:0;
          var data = {
            'itemNumId': itemNumId,
            'styleNumId':styleNumId,
            // 'shopId': SpUtil.getInt('storeShopNum').toString(),
            'shopId': shopId,
            'ecStyleNumId':ecStyleNumId,
            'typeIndex': typeIndex,
          };
          Get.toNamed(RouteConfig.goodsDetail+'?itemNumId=$itemNumId&styleNumId=$styleNumId&shopId=$shopId&ecStyleNumId=$ecStyleNumId&typeIndex=$typeIndex', arguments: data);
        },
        child: Row(
          children: [
            // if(state.products.length > 0)
            CachedImage(width: 260.w, height: 260.w, path: state.products[index]['image_default_id'] ?? 'https://xlsstatic.zrhsh.com/200000002330~2108130020104.jpg'),
            //path:'https://xlsstatic.zrhsh.com/200000002330~2108130020104.jpg'),
            SizedBox(width: 24.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Container(constraints: BoxConstraints(minHeight: 140.w), child: Text(state.products[index]['item_title'], style: TextStyle(color: EsColors.Title, fontSize: EsSizes.SM * 2.sp, fontWeight: EsFontWeights.Normal))),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          // Text('已抢${state.products[index]['seckill_qty']}件',
                          // style: TextStyle(
                          //     color: EsColors.ContentSecondary,
                          //     fontSize: EsSizes.XS * 2.sp,
                          //     fontWeight: EsFontWeights.Normal)),
                          Row(
                            children: [
                              Text('￥${state.products[index]['seckill_price']}', style: TextStyle(color: EsColors.Primary, fontSize: EsSizes.MD * 2.sp, fontWeight: EsFontWeights.Normal)),
                              // Visibility(
                              //   visible: state.products[index]
                              //               ['commission_amount'] !=
                              //           null &&
                              //       state.products[index]['commission_amount'] >
                              //           0,
                              //   child: Padding(
                              //     padding:
                              //         const EdgeInsets.only(left: 4, top: 5),
                              //     child: Text(
                              //         '赚:${state.products[index]['commission_amount'] ?? 0.0.toStringAsFixed(0)}',
                              //         style: TextStyle(
                              //             color: EsColors.Primary,
                              //             fontSize: EsSizes.XS * 2.sp,
                              //             fontWeight: EsFontWeights.Normal)),
                              //   ),
                              // )
                            ],
                          ),
                          if (state.products[index]['mkt_price'] >= state.products[index]['price'])
                            Text('￥${state.products[index]['mkt_price']}', //原价
                                style: TextStyle(decoration: TextDecoration.lineThrough, color: EsColors.ContentSecondary, fontSize: EsSizes.XS * 2.sp, fontWeight: EsFontWeights.Normal)),
                        ],
                      ),
                      Expanded(child: SizedBox()),
                      GestureDetector(
                        onTap: () {
                          print('马上抢');
                          if (kIsWeb) {
                            /// 跳转到app失败 进入下载页或者提示系统浏览器打开
                            Future.delayed(Duration(seconds: 1), () {
                              if (isWechat()) {
                                // toast('请在系统浏览器打开本页面');
                                // Navigator.of(context).pop();
                                setState(() {
                                  state.showTip = true;
                                });
                              } else {
                                /// 进入下载页
                                webpay(Config.WEB_DOWN_URL + "download.html");
                              }
                            });
                            webpay("yinpinhui://zrhsh.com/app");
                          } else {
                            if (SpUtil.getString('token') == null || SpUtil.getString('token').isEmpty) {
                              Get.toNamed(RouteConfig.mallLogin);
                            }
                            var shop_num_id =Get.arguments!=null? Get.arguments['model']['results'][index]['ec_shop_num_id']:null;
                            print(SpUtil.getInt('storeShopNum'));
                            Get.toNamed(RouteConfig.settleAccounts, arguments: {
                              // 'shop_id': SpUtil.getInt('storeShopNum'),
                              'shopId': state.products[index]['ec_shop_num_id:'] != null ? state.products[index]['ec_shop_num_id:'].toString() : SpUtil.getInt('storeShopNum'),
                              'shop_id':shop_num_id==null? SpUtil.getInt('storeShopNum'):shop_num_id,
                              "item_num_id": state.products[index]['item_num_id'],
                              "style_num_id": state.products[index]['style_num_id'],
                              "ec_style_num_id": state.products[index]['ec_style_num_id'],
                              'shopnum': 1
                            });
                          }

                          // logic.requestAddGoods(
                          //     state.products[index]['item_num_id'],
                          //     state.products[index]['style_num_id'],
                          //     state.products[index]['ec_style_num_id']);
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(vertical: 10.w, horizontal: 24.w),
                          child: Text('马上抢', style: TextStyle(color: EsColors.White, fontSize: EsSizes.MD * 2.sp, fontWeight: EsFontWeights.Medium)),
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                              ///渐变色
                              colors: [Color(0xffea5504), Color(0xffffbd00)],
                            ),
                            borderRadius: BorderRadius.all(Radius.circular(30.w)),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}
